import React, { useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';
import Svg, { Path, Circle, Rect, G } from 'react-native-svg';

interface SvgIconProps {
    uri: string;
    width?: number;
    height?: number;
    style?: any;
}

const SvgIcon: React.FC<SvgIconProps> = ({ uri, width = 28, height = 28, style }) => {
    const [svgContent, setSvgContent] = useState<string | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);

    useEffect(() => {
        setLoading(true);
        setError(false);

        if (!uri) {
            setLoading(false);
            setError(true);
            return;
        }

        fetch(uri)
            .then(res => {
                if (!res.ok) {
                    throw new Error(`HTTP error! status: ${res.status}`);
                }
                return res.text();
            })
            .then(text => {
                setSvgContent(text);
                setLoading(false);
            })
            .catch(err => {
                console.error('SVG加载失败:', err);
                setError(true);
                setLoading(false);
            });
    }, [uri]);

    if (loading) {
        return (
            <View style={[{ width, height, justifyContent: 'center', alignItems: 'center' }, style]}>
                <ActivityIndicator size="small" color="#007AFF" />
            </View>
        );
    }

    if (error || !svgContent) {
        // 返回一个默认的占位符图标
        return (
            <View style={[{ width, height, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0', borderRadius: 4 }, style]}>
                <Svg width={width * 0.6} height={height * 0.6} viewBox="0 0 24 24">
                    <Path
                        d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
                        fill="#999"
                    />
                </Svg>
            </View>
        );
    }

    // 尝试解析SVG内容并渲染
    try {
        // 提取SVG的viewBox
        const viewBoxMatch = svgContent.match(/viewBox=["']([^"']+)["']/);
        const viewBox = viewBoxMatch ? viewBoxMatch[1] : "0 0 24 24";

        // 提取SVG的路径内容
        const pathMatch = svgContent.match(/<path[^>]*>/g);
        const circleMatch = svgContent.match(/<circle[^>]*>/g);
        const rectMatch = svgContent.match(/<rect[^>]*>/g);

        if (pathMatch || circleMatch || rectMatch) {
            return (
                <Svg width={width} height={height} viewBox={viewBox} style={style}>
                    {pathMatch?.map((path, index) => {
                        const dMatch = path.match(/d=["']([^"']+)["']/);
                        const fillMatch = path.match(/fill=["']([^"']+)["']/);
                        const strokeMatch = path.match(/stroke=["']([^"']+)["']/);
                        const strokeWidthMatch = path.match(/stroke-width=["']([^"']+)["']/);

                        return (
                            <Path
                                key={index}
                                d={dMatch ? dMatch[1] : ""}
                                fill={fillMatch ? fillMatch[1] : "#000"}
                                stroke={strokeMatch ? strokeMatch[1] : undefined}
                                strokeWidth={strokeWidthMatch ? parseFloat(strokeWidthMatch[1]) : undefined}
                            />
                        );
                    })}
                    {circleMatch?.map((circle, index) => {
                        const cxMatch = circle.match(/cx=["']([^"']+)["']/);
                        const cyMatch = circle.match(/cy=["']([^"']+)["']/);
                        const rMatch = circle.match(/r=["']([^"']+)["']/);
                        const fillMatch = circle.match(/fill=["']([^"']+)["']/);

                        return (
                            <Circle
                                key={index}
                                cx={cxMatch ? parseFloat(cxMatch[1]) : 12}
                                cy={cyMatch ? parseFloat(cyMatch[1]) : 12}
                                r={rMatch ? parseFloat(rMatch[1]) : 10}
                                fill={fillMatch ? fillMatch[1] : "#000"}
                            />
                        );
                    })}
                    {rectMatch?.map((rect, index) => {
                        const xMatch = rect.match(/x=["']([^"']+)["']/);
                        const yMatch = rect.match(/y=["']([^"']+)["']/);
                        const widthMatch = rect.match(/width=["']([^"']+)["']/);
                        const heightMatch = rect.match(/height=["']([^"']+)["']/);
                        const fillMatch = rect.match(/fill=["']([^"']+)["']/);

                        return (
                            <Rect
                                key={index}
                                x={xMatch ? parseFloat(xMatch[1]) : 0}
                                y={yMatch ? parseFloat(yMatch[1]) : 0}
                                width={widthMatch ? parseFloat(widthMatch[1]) : 24}
                                height={heightMatch ? parseFloat(heightMatch[1]) : 24}
                                fill={fillMatch ? fillMatch[1] : "#000"}
                            />
                        );
                    })}
                </Svg>
            );
        }
    } catch (err) {
        console.error('SVG解析失败:', err);
    }

    // 如果解析失败，返回占位符
    return (
        <View style={[{ width, height, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0', borderRadius: 4 }, style]}>
            <Svg width={width * 0.6} height={height * 0.6} viewBox="0 0 24 24">
                <Path
                    d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
                    fill="#999"
                />
            </Svg>
        </View>
    );
};

export default SvgIcon; 